﻿Function New-EventGroup
{
  [CmdletBinding()]
  param
  (
    [parameter(Position=0,
               Mandatory=$true)]
    [String]
    $FriendlyName,

    [parameter(Position=1,
               Mandatory=$true)]
    [int]
    $Order,

    [parameter(Position=2)]
    [string]
    $Description
  )

  Begin
  {
    # Lock the group list XML file while adding the event group.
    $Created = $False
    $Script:GroupMutex = New-Object System.Threading.Mutex($True,"eventlib_write_group_xml",[ref]$Created)

    if ($Created -eq $False)
    {
      try `
      {
        $Lock = $Script:GroupMutex.WaitOne(2000)
      }
      catch [System.Threading.AbandonedMutexException] `
      {
        Write-Warning "Caught AbandonedMutexException.  Consider checking the Event Group list for consistency."
      }
    }
    else
    {
      $Lock = $True
    }

    if ($Lock -eq $False)
    {
      $Exception = New-Object System.TimeoutException "Timed out waiting to lock the eventlib_write_group_xml mutex."
      throw $Exception
    }
  }

  Process
  {
    $GroupList = $(Get-EventGroup)

    if ($GroupList -eq $Null)
    {
      $GroupList = @()
      $HighestNumber = -1
    }
    elseif ($GroupList -isnot [system.array])
    {
      $GroupList = @($GroupList)
      $HighestNumber = $($($GroupList | Sort-Object -Descending Number)[0]).Number
    }
    else
    {
      $HighestNumber = $($($GroupList | Sort-Object -Descending Number)[0]).Number
    }

    if ($($GroupList | Where-Object {$_.FriendlyName -eq $FriendlyName}) -ne $Null)
    {
        $Exception = New-Object System.ArgumentException "A parameter is invalid.  An Event Group with Friendly Name '$FriendlyName' already exists."
        throw $Exception
    }
    if ($($GroupList | Where-Object {$_.Order -eq $Order}) -ne $Null)
    {
        $Exception = New-Object System.ArgumentException "A parameter is invalid.  An Event Group with order '$Order' already exists."
        throw $Exception
    }

    $EventGroup = New-Object EventGroup

    $EventGroup.Number = $HighestNumber + 1
    $EventGroup.FriendlyName = $FriendlyName
    $EventGroup.Order = $Order
    $EventGroup.Description = $Description

    $GroupList += $EventGroup

    Export-Clixml -Path $Script:GroupXMLPath -InputObject $GroupList
  }

  End
  {
    $Script:GroupMutex.ReleaseMutex()
  }
}